import axios from "axios";
import { ElMessage } from 'element-plus'
import { useUserGlobalStore } from '@/store/UserGobalStore/index.js'
import { useTabsStore } from '@/store/tabs/index.js'
import { useMenuStore } from '@/store/menu/index.js'
import router from '@/router/index.js'

const http = axios.create({
    baseURL: 'http://localhost:9001',
    timeout: 6000,
})


http.interceptors.request.use(async config => {

    const token = localStorage.getItem("token") || ''

    config.headers['token'] = token
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
http.interceptors.response.use(
    response => {
        let res = response.data;
        if (res.code == 200) {
            return res.data
        }
        else if (res.code == 401) {
            useUserGlobalStore().reset()
            useMenuStore().reset()
            useTabsStore().resetTabs()
            localStorage.clear();
            ElMessage.error(res.msg || '操作失败')
            router.push({
                path: '/login'
            })
        }
        else {
            ElMessage.error(res.msg || '操作失败')
            return false;
        }
    },
    error => {
        console.log('err', error) // for debug
        return Promise.reject(error)
    }
)
export default http